package com.cal.utms.core;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.cal.utms.entity.Menu;
import com.cal.utms.entity.MenuItem;
import com.cal.utms.util.HibernateUtil;

public class MenuItemDao {

	public Menu getMenuByName(String name) {

		Session session = HibernateUtil.getSession().openSession();
		Transaction transaction = null;
		Menu menu = null;
		try {
			transaction = session.beginTransaction();
			menu = (Menu) session.createQuery("From Menu M where M.uniqueName=:name").setParameter("name", name).uniqueResult();
			transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return menu;
	}

	@SuppressWarnings("unchecked")
	public List<MenuItem> getAllMenuItem() {

		Session session = HibernateUtil.getSession().openSession();
		Transaction transaction = null;
		List<MenuItem> items = new ArrayList<MenuItem>();
		try {
			transaction = session.beginTransaction();
			items = session.createQuery("From MenuItem M").list();
			transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return items;
	}

	@SuppressWarnings("unchecked")
	public List<MenuItem> getScreenByGroupId(int groupid) {
		Session session = HibernateUtil.getSession().openSession();
		Transaction transaction = null;
		List<MenuItem> menus = new ArrayList<MenuItem>();
		try {
			transaction = session.beginTransaction();
			menus = session.createQuery("From MenuItem M where M.screen.id IN (select UG.id.screenId from UserGroupScreen UG where UG.id.userGroupId=:groupid)")
					.setParameter("groupid", groupid).list();
			transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}

		return menus;
	}

}
